"""
Case Type   : 功能
Case Name   : 并发插入数据并删除
Create At   : 2020/11/30
Owner       : liumin
Description :
    1.创建表
    2.插入数据
    3.创插入数据的同时删除数据
    4.重复执行2-3 100次
Expect      :
    1.创建表成功
    2.插入数据成功
    3.删除数据成功
    4.无
History     :
    Modified by peilinqian executeDbsql公共方法优化同步修改用例
    Modified by ningyali 优化用例解决一致性问题
"""
import os
import unittest

from testcase.utils.ComThread import ComThread
from testcase.utils.CommonSH import CommonSH, RestartDbCluster
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class Concurrently(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.pri_sh = CommonSH(self.nodes_tuple[0])
        self.pri_user = self.pri_sh.node
        self.log = Logger()
        self.Constant = Constant()
        self.t_name = 't_dbsystem_case224'
        self.i_name = 'i_dbsystem_case224'
        self.log.info(f'-----{os.path.basename(__file__)} start-----')

    def test_in_select(self):
        self.log.info('-----create table-----')
        sql = f'drop table if exists {self.t_name};' \
              f'create table {self.t_name}(' \
              f'id int, ' \
              f'first_name text, ' \
              f'last_name text);'
        result = self.pri_sh.executDbSql(sql)
        self.assertIn(self.Constant.CREATE_TABLE_SUCCESS, result)

        for i in range(100):
            self.log.info(f'-----round {i}-----')
            self.log.info('-----insert data-----')
            sql = f'insert into {self.t_name} ' \
                  f'select id, md5(random()::text), md5(random()::text) ' \
                  f'from (' \
                  f'select * from generate_series(1,1000000) as id) as x;'
            create_index_thread = ComThread(self.pri_sh.executDbSql,
                                            args=(sql,))
            create_index_thread.setDaemon(True)
            create_index_thread.start()

            self.log.info('----- delete data-----')
            sql = f'delete from {self.t_name} where id>70000 and id <800000;'
            result = self.pri_sh.executDbSql(sql)
            self.assertIn('DELETE', result)

            self.log.info('-----check insert data result-----')
            create_index_thread.join(10 * 60)
            create_idx_result = create_index_thread.get_result()
            self.log.info(create_idx_result)
            self.assertIn('INSERT', create_idx_result)

    def tearDown(self):
        self.log.info('-----this is tearDown-----')
        self.log.info('-----drop table-----')
        sql = f'drop table if exists {self.t_name};'
        result = self.pri_sh.executDbSql(sql)
        self.log.info(result)
